﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Linq;
using Ue.Extensions;
using Ue.Core.DynamicReflection;

namespace Ue.Eagle.Runtime.Configuration
{
    /// <summary>
    /// 扩展点的扩展配置基类
    /// 所有扩展点扩展配置的ConfigurationElement都需要从这个类继承
    /// </summary>
    public class PluginExtensionElement : ConfigurationElement
    {
        [ConfigurationProperty(
            PluginConfigurationConstants.PluginExtensionPointIdAttributeName)]
        public string PointId
        {
            get { return this[PluginConfigurationConstants.PluginExtensionPointIdAttributeName] as string; }
            set { this[PluginConfigurationConstants.PluginExtensionPointIdAttributeName] = value; }
        }

        internal string ElementOuterXml { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="acquireExtensionPointElement">根据pointId取得PluginExtenisonPointElement</param>
        /// <returns></returns>
        internal PluginExtensionElement DeserializeExtensionElement(Func<string,Type> acquireExtensionElementType)
        {
            var type = acquireExtensionElementType(this.PointId);
            if (type == null)
            {
                return null;
            }

            try
            {
                var element = Activator.CreateInstance(type) as PluginExtensionElement;
                if (element == null)
                {
                    return null;
                }

                using (XmlReader reader = XmlReader.Create(new StringReader(this.ElementOuterXml)))
                {
                    reader.MoveToContent();
                    element.DeserializeElement(reader, false);
                }

                return element;
            }
            catch
            {
                return null;
            }
        }
    }
}
